<template>
  <el-form ref="form" :model="form" label-width="80px" :rules="rules">
    <el-container>
      <!--  -->
      <el-aside width="2">
        <el-upload
          ref="upload"
          :show-file-list="false"
          :on-change="uploadChange"
          :on-error="error"
          :on-success="success"
          :auto-upload="false"
          :action="httpUrl"
          :data="form"
          name="file"
          with-credentials
        >
          <img v-if="file" :src="file" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-aside>
      <el-main>
        <el-form-item label="书籍名称" prop="bookName">
          <el-input v-model="form.bookName"></el-input>
        </el-form-item>
        <el-form-item label="类别" required>
          <el-radio v-model="catalogGender" @change="radioItem" label="男生"
            >男生</el-radio
          >
          <el-radio v-model="catalogGender" @change="radioItem" label="女生"
            >女生</el-radio
          >
        </el-form-item>
        <el-form-item label="分类" v-if="showCatalog > 0" prop="catalogName">
          <el-col :span="11">
            <el-select
              placeholder="请选择"
              @change="selectItem"
              v-model="form.catalogParent"
            >
              <el-option
                v-for="item in catalogBranch"
                :key="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="11">
            <el-select
              v-model="form.catalogName"
              :disabled="isDisabled"
              placeholder="请选择"
            >
              <el-option
                v-for="item in catalogList"
                :key="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="作品简介">
          若未填，使用默认「来xxxxx阅读我的更多作品吧！」
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.synopsis"
            placeholder="不超过250字"
          ></el-input>
        </el-form-item>
        <el-form-item label="试读数">
          <el-input-number v-model="form.promotion" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="编辑"> 随机分配 </el-form-item>
        <el-form-item>
          <el-button type="primary" v-if="!isUpdate" @click="submitUpload"
            >立即创建</el-button
          >
          <el-button type="primary" v-else @click="theUpdateBook"
            >立即修改</el-button
          >
          <el-button>取消</el-button>
        </el-form-item>
      </el-main>
    </el-container>
  </el-form>
</template>

<script>
import { getCatalogAll, selectBook, updateBook } from "@/api";

export default {
  data() {
    return {
      isUpdate: this.$route.params.bookId != 0,
      book: {
        bookImgUrl:
          "http://localhost:8001/resource/BOOK/COVER/80741546_p0_master1200.jpg",
        bookName: "三体",
        bookUrl: "C:\\Users\\YKH\\Desktop\\resource\\BookWarehouse\\2\\三体",
        catalogName: "东方玄幻",
        chapter: 4,
        chapterServiceCharge: null,
        chapterUnitPrice: null,
        continuedState: "SERIALIZE",
        createTime: "2022-05-17 17:29:20:000",
        deleteState: 0,
        earnings: null,
        earningsOther: null,
        editorId: null,
        id: 24,
        integral: null,
        lastChapterId: 65,
        lastChapterName: "射手和农场主(1)",
        promotion: 30,
        recentIntegral: null,
        recentVisit: 0,
        saleState: "OFF_SALE",
        serviceCharge: null,
        subscription: null,
        synopsis: "来xxxxx阅读我的更多作品吧！",
        updateTime: "2022-05-17 18:23:29:000",
        wordCount: 22969,
        writerId: 2,
      },
      //是否显示分类选中框
      showCatalog: 0,
      //第二个选择框是否可用
      isDisabled: true,
      httpUrl: "http://localhost:8001/api/writer/addBook/0",
      file: "",
      form: {
        bookName: "",
        catalogParent: "",
        catalogName: "",
        synopsis: "",
        promotion: 30,
      },
      //分类
      catalogList: [],
      //男生，或者女生的分支
      catalogBranch: [],
      //全部
      catalogAll: [],
      //男，女
      catalogGender: "",
      //校验
      rules: {
        bookName: [
          { required: true, message: "请输入书籍名称", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        catalogName: [
          { required: true, message: "请选择书籍分类", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    selectItem(val) {
      this.form.catalogName = "";
      if (this.isDisabled) {
        this.isDisabled = false;
      }
      for (let i = 0; i < this.catalogBranch.length; i++) {
        console.log(this.catalogBranch[i]);
        if (val == this.catalogBranch[i].name) {
          this.catalogList = this.catalogBranch[i].children;
          break;
        }
      }
    },
    radioItem(val) {
      this.form.catalogName = "";
      this.form.catalogParent = "";
      console.log("选中");
      for (let i = 0; i < this.catalogAll.length; i++) {
        console.log(this.catalogAll[i]);
        if (val == this.catalogAll[i].name) {
          this.showCatalog += 1;
          this.catalogBranch = this.catalogAll[i].children;
          break;
        }
      }
    },
    //失败
    error(err, file, fileList) {
      console.log("失败");
    },
    //成功
    success(response, file, fileList) {
      console.log(response, "--------------------");
      if (response.code == 0) {
        this.$message.success("作品创建成功");
      }else{
        this.$message.error("作品创建失败"+response.msg);
      }
    },
    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     */
    uploadChange(file, fileList) {
      this.file = URL.createObjectURL(file.raw);
    },
    //提交修改
    theUpdateBook() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log("修改");
          if (!this.form.synopsis) {
            this.form.synopsis = "来xxxxx阅读我的更多作品吧！";
          }
          
          //触发组件的action
          console.log("--------upload----------")
          if (this.$refs.upload.uploadFiles.length>0) {
            //文件不存在时，submit的请求不会被触发
            this.$refs.upload.submit();
          } else {
            //手动构造一个请求，提示
            updateBook(this.$route.params.bookId,this.form)
              .then(({ data }) => {
                if(data.code == 0){
                  this.$message.success("修改成功");
                }else{
                  this.$message.success("修改失败");
                }
              })
              .catch((err) => {});
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //提交保存
    submitUpload() {
      console.log("1", this);
      console.log("2", this.$refs);
      console.log("3", this.$refs.form);
      //form.validate校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log("提交");
          if (!this.form.synopsis) {
            this.form.synopsis = "来xxxxx阅读我的更多作品吧！";
          }
          //触发组件的action
          if (this.file) {
            //文件不存在时，submit的请求不会被触发
            this.$refs.upload.submit();
          } else {
            //手动构造一个请求，提示
            this.$message.error("书籍封面是必选的");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  created() {
    getCatalogAll()
      .then(({ data }) => {
        this.catalogAll = data.data;
      })
      .catch((err) => {});
    if (this.isUpdate) {
      console.log("----------init---------");
      this.httpUrl = `http://localhost:8001/api/writer/addBook/${this.$route.params.bookId}`;
      selectBook(this.$route.params.bookId)
        .then(({ data }) => {
          let d = data.data;
          console.log("data", data);
          this.form = {
            bookName: d.bookName,
            catalogParent: d.catalogParent,
            catalogName: d.catalogName,
            synopsis: d.synopsis,
            promotion: d.promotion,
          };
          this.file = d.bookImgUrl;
          this.catalogGender = d.startCatalog;
          this.radioItem(d.startCatalog);
          this.form.catalogParent = d.catalogParent;
          this.form.catalogName = d.catalogName;
          this.showCatalog += 1;
          this.isDisabled = false;
        })
        .catch((err) => {});
    }
  },
};
</script>

<style scoped>
/* .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
} */
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>